﻿using System;
using System.Collections.Generic;
using System.Xml;
using Coffee.DataMappers;

namespace Coffee
{

    public class DataMapperFactory
    {
        protected static List<Type> RegisteredMappers { get; set; }

        public static void RegisterMapper(Type mapper)
        {
            if (RegisteredMappers == null) RegisteredMappers = new List<Type>();
            RegisteredMappers.Add(mapper);
        }

        public static IDataMapper CreateMapper(XmlNode parentcfg)
        {
            XmlNode dmnroot = parentcfg.SelectSingleNode("datamapper");

            if (dmnroot != null)
            {
                string mapper = dmnroot.Attributes["name"].Value;
                XmlNode dmncfg = dmnroot.SelectSingleNode("configuration");

                var t = RegisteredMappers.Find(m => m.Name.Equals(mapper + "Mapper"));

                if (t != null)
                {
                    if (dmncfg != null)
                    {
                        return (IDataMapper)Reflection.CreateLocalObject(t, new Type[] { typeof(XmlNode) }, new object[] { parentcfg });
                    }
                    else
                    {
                        return (IDataMapper)Reflection.CreateLocalObject(t);
                    }
                }
            }

            return null;
        }
    }
}
